import service from "../../service/service";
import {useRouter} from "vue-router"
import {onMounted, ref} from "vue";

export default function Home() {
    const router = useRouter()

    let ArticleList = ref([])
    let articleTotal = ref(0)
    let pattern = /[`~!@#_$%^&*()=|{}'',\\\[\\\].<>/?~！@#￥……&*（）——|{}‘；”“'。、\s]/g
    onMounted(() => {
        loading.value = true
        // 获取第一页文章
        service.getArticleList().then(r => {
            let data = r.data['msg']['data']
            if (r.data.code === 200) {
                articleTotal.value = r.data['msg']['total']
                for (let i = 0; i < data.length; i++) {
                    let tmpObj = {}
                    let content = data[i]['Content'].substring(0, 100)
                    content = content.replace(pattern, '')
                    tmpObj.id = data[i]['ID']
                    tmpObj.title = data[i]['Title']
                    tmpObj.sort = data[i]['Class']
                    tmpObj.content = content
                    tmpObj.author = data[i]['Author']
                    ArticleList.value.push(tmpObj)
                }
            }
            loading.value = false
        })
    })
    const toArticleBtn = (id) => {
        router.push({
            path: '/article_details',
            query: {
                id: id
            }
        })
    }

    const newPagesBtn = (new_page_num) => {
        let data = {
            pages_size: 10,
            this_page: new_page_num
        }
        service.pagingFind(data).then(r => {
            ArticleList.value = []
            let data = r.data['msg']['data']
            if (r.data.code === 200) {
                articleTotal.value = r.data['msg']['total']
                for (let i = 0; i < data.length; i++) {
                    let tmpObj = {}
                    let content = data[i]['Content'].substring(0, 100)
                    content = content.replace(pattern, '')
                    tmpObj.id = data[i]['ID']
                    tmpObj.title = data[i]['Title']
                    tmpObj.sort = data[i]['Class']
                    tmpObj.content = content
                    tmpObj.author = data[i]['Author']
                    ArticleList.value.push(tmpObj)
                }
            }
        })
    }

    let loading = ref(false)

    return {
        loading,
        toArticleBtn,
        ArticleList,
        articleTotal,
        newPagesBtn
    }
}